import React, { Component } from 'react';
import { Provider } from 'mobx-react'
import { Route, Switch, withRouter } from 'react-router-dom' 
import Cookies from 'js-cookie'

import stores from './store/store.js'
import LoginView from 'pages/Login/LoginView.jsx'
import Layout from 'pages/Layout/Layout.jsx'
import config from 'config/config.js'


// 使用@withRouter可以拿到三个对象：history,location,match
@withRouter
class Routes extends Component {
  constructor(props) {
    super(props)
    this.pathname = this.props.location.pathname
  }

  // 检查是否cookie里面有username值，否则跳回去登录
  checkCookie = () => {
    if(this.pathname != '/login') {
      if(!Cookies.get(config.cookie.username)) {
        this.props.history.replace('/login')
      }
    }
  }

  componentWillMount() {
    this.checkCookie()
  }
  
  componentWillReceiveProps(nextProps) {
    this.pathname = nextProps.location.pathname
    this.checkCookie()
  }

	render() {
		return (
      <Provider {...stores}>
        <Switch>
          <Route path='/login' exact component={LoginView}></Route>
          <Route path="/" component={Layout}></Route>
        </Switch>
      </Provider>
		)
	}
}

export default Routes